<template>
  <j-modal
    title="采购单变更"
    :width="1350"
    :visible="modalVisible"
    :maskClosable="false"
    switchFullscreen
    @cancel="clickCancel"
  >
    <a-spin :spinning="submitLoading">
      <a-form-model ref="form" :model="formData" :rules="rules">
        <a-divider orientation="left"> 基本信息 </a-divider>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="采购人" prop="purchaser" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-url-select
                :disabled="true"
                v-model="formData.purchaser"
                placeholder="请选择采购人"
                url="/sys/user/getAllUsernameByOrg"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="成本中心" prop="costCenterId" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-url-select
                ref="costCenterId"
                :disabled="true"
                placeholder="请选择成本中心"
                v-model="formData.costCenterId"
                :allowClear="false"
                url="/sys/costCenter/queryAllByUserId"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="采购方式" prop="purchaseWay" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                placeholder="请选择采购方式"
                :disabled="true"
                v-model="formData.purchaseWay"
                dictCode="purchase_way"
                :allowClear="false"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="收货仓库" prop="warehouse" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-url-select
                :disabled="true"
                v-model="formData.warehouse"
                placeholder="请选择收货仓库"
                url="/hzkj-wms/wms/warehouse/queryWarehouseByUserId?type=1"
                :optionDiy="optionWarehouseDiy"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="运输方式" prop="transportWay" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                :disabled="true"
                placeholder="请选择运输方式"
                v-model="formData.transportWay"
                dictCode="purchase_transport_way"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="预计到货时间"
              prop="expectArrivalTime"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-date-picker
                :disabled="true"
                v-model="formData.expectArrivalTime"
                valueFormat="YYYY-MM-DD"
                style="width: 100%"
                placeholder="请选择预计到货时间"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="给仓库留言"
              prop="warehouseRemark"
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 2 },
              }"
              :wrapperCol="wrapperCol"
            >
              <a-textarea
                :disabled="true"
                v-model="formData.warehouseRemark"
                rows="2"
                placeholder="请输入留言"
                :maxLength="128"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="备注"
              prop="remark"
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 2 },
              }"
              :wrapperCol="wrapperCol"
            >
              <a-textarea
                :disabled="true"
                v-model="formData.remark"
                rows="2"
                placeholder="请输入备注"
                :maxLength="128"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item
              label="变更原因"
              prop="changeCause"
              :labelCol="{
                xs: { span: 24 },
                sm: { span: 2 },
              }"
              :wrapperCol="wrapperCol"
            >
              <a-textarea v-model="formData.changeCause" rows="2" placeholder="请输入变更原因" :maxLength="128" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left"> 产品费用 </a-divider>
        <div class="btn-box">
          <a-button type="primary" icon="plus" @click="showProductCheck = true" style="margin-right: 10px"
            >添加产品</a-button
          >
          <a-alert message="允许添加多个供应商产品，不同供应商保存草稿后会按照供应商拆分为多个采购单。" banner />
        </div>
        <a-table
          bordered
          :pagination="false"
          :scroll="{ x: true, y: 400 }"
          :columns="formColumns"
          :data-source="formData.productDetailChangeList"
          rowKey="skuCode"
        >
          <template #imgSlot="text, record">
            <a-popover trigger="hover" placement="right">
              <template #content>
                <div class="popover-preview-box">
                  <img :src="record.imgUrl" />
                </div>
              </template>
              <viewer :images="[record.imgUrl]" class="img-box">
                <img v-show="record.imgUrl" class="sku-img" :src="record.imgUrl" />
              </viewer>
            </a-popover>
          </template>
          <template #detailSlot="text, record">
            <div>类目:{{ record.categoryName }}</div>
            <div>名称:{{ record.nameCn }}</div>
            <div>颜色/尺寸:{{ record.color }};{{ record.size }}</div>
            <div>单品规格(cm):{{ record.singleSpec }}</div>
            <div>毛重(KG):{{ record.gw }}</div>
            <div>
              质检方式:<span v-if="record.qualityType == 1">免检</span><span v-if="record.qualityType == 3">全检</span
              ><span v-if="record.qualityType == 2">抽检</span>
            </div>
          </template>
          <template #supplierSlot="text, record">
            <template v-if="record.supplierId">
              <div>供应商:{{ record.supplierName }}</div>
              <div class="link-item">
                <div>采购链接:</div>
                <a-tooltip :overlayStyle="{ 'min-Width': '700px' }">
                  <template slot="title"> {{ record.url || '-' }} </template>
                  <div class="link">
                    {{ record.url || '-' }}
                  </div>
                </a-tooltip>
              </div>
              <div>
                属性:
                <div v-if="record.supplierType == 1">
                  <div v-for="item1 in record.attribute" :key="item1.attributeID">
                    {{ item1.attributeName }}:
                    <span v-for="(val2, index2) in item1.checkVal" :key="index2">{{ val2 }}；</span>
                  </div>
                </div>
                <div v-else>{{ record.attribute || '-' }}</div>
              </div>
              <div>最低起订量:{{ record.lowCount }}</div>
            </template>
            <template v-else>
              <div class="c-red">未找到供应商</div>
            </template>
          </template>
          <template #specSlot="text, record">
            <div>
              供应商规格:
              <span v-if="record.supplierId" :class="{ 'c-red': record.specsSup > 1 }">{{ record.specsSup }}</span
              ><span v-else>-</span>/组
            </div>
            <div>
              入库规格:<span v-if="record.supplierId" :class="{ 'c-red': record.specsMy > 1 }">{{
                record.specsMy
              }}</span
              ><span v-else>-</span>/组
            </div>
            <a-tooltip placement="top">
              <template slot="title">
                供应商规格{{ record.specsSup }}：代表向供应商下单1个含{{ record.specsSup }}件；入库规格{{
                  record.specsMy
                }}：代表仓库按照{{ record.specsMy }}个 1 组入库。
              </template>
              <a-icon type="info-circle" />
            </a-tooltip>
          </template>
          <template #purchaseQuantityNew>
            <span class="c-red">*新</span>采购数量
            <div>(仓库应收)</div></template
          >
          <template #purchaseQuantityNewSlot="text, record, index">
            <a-form-model-item
              :prop="'productDetailChangeList.' + index + '.purchaseQuantityNew'"
              :rules="{
                required: true,
                message: '数量不能为空',
                trigger: 'blur',
              }"
            >
              <a-input-number v-model="record.purchaseQuantityNew" :min="1" :max="99999999" :step="1" :precision="0" />
            </a-form-model-item>
          </template>
          <template #unitPriceNew> <span class="c-red">*新</span>采购单价(元) </template>
          <template #unitPriceNewSlot="text, record, index">
            <a-form-model-item
              :prop="'productDetailChangeList.' + index + '.unitPriceNew'"
              :rules="{
                required: true,
                message: '单价不能为空',
                trigger: 'blur',
              }"
            >
              <a-input-number v-model="record.unitPriceNew" :min="1" :max="999999.999" :step="1" :precision="3" />
            </a-form-model-item>
          </template>
          <template #totalPriceNew> <span class="c-red">*新</span>采购总价(元) </template>
          <span slot="action" slot-scope="text, record, index">
            <a v-if="!record.isOldProduct" @click="delProduct(index)">删除</a>
          </span>
        </a-table>
        <a-row style="margin-top: 15px">
          <a-col :span="6">
            <a-form-model-item label="运费" prop="shippingFeeOld" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input-number
                :disabled="true"
                v-model="formData.shippingFeeOld"
                :min="1"
                :max="999999.999"
                :step="1"
                :precision="3"
                style="width: 80%"
              /><span class="input-number-unit">元</span>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item
              prop="shippingFeeNew"
              :rules="{ required: true, message: '请输入新运费!' }"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <template slot="label"> <span style="color: red">新</span>运费 </template>
              <a-input-number
                v-model="formData.shippingFeeNew"
                :min="1"
                :max="999999.999"
                :step="1"
                :precision="3"
                style="width: 80%"
              /><span class="input-number-unit">元</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left"> 支付信息 </a-divider>
        <div class="pay-msg">
          单据费用：采购总量 = <span class="c-red">{{ purchaseTotalNew }}</span
          ><span class="old-size">({{ purchaseTotalOld }})</span>，采购总金额 =
          <span class="c-red"
            >{{ totalAmountNew }}<span class="old-size">({{ totalAmountOld }})</span></span
          >
          <span>元</span>
        </div>
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="结算类型" prop="settlementType" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                placeholder="请选择"
                v-model="formData.settlementType"
                dictCode="purchase_settlement_type"
                :disabled="true"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="结算方式" prop="settlementWay" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                placeholder="请选择"
                v-model="formData.settlementWay"
                dictCode="purchase_settlement_way"
                :disabled="true"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="支付方式" prop="paymentWay" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-search-select-tag-new
                placeholder="请选择"
                v-model="formData.paymentWay"
                dictCode="purchase_payment_way"
                :disabled="true"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="供应商订单"
              prop="supplierOrderNoOld"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
            >
              <a-input :disabled="true" v-model="formData.supplierOrderNoOld" placeholder="请输入供应商订单号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="支付单号" prop="paymentOrderNoOld" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input :disabled="true" v-model="formData.paymentOrderNoOld" placeholder="请输入支付单号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="付款时间" prop="paymentTimeOld" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-date-picker
                showTime
                :disabled="true"
                valueFormat="YYYY-MM-DD HH:mm:ss"
                v-model="formData.paymentTimeOld"
                style="width: 100%"
                placeholder="请选择付款时间"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="支付凭证" prop="paymentVoucherOld" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-upload-oss :disabled="true" v-model="formData.paymentVoucherOld" fileType="file" :number="1" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="8">
            <a-form-model-item prop="supplierOrderNoNew" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <template slot="label"> <span style="color: red">新</span>供应商订单 </template>
              <a-input v-model="formData.supplierOrderNoNew" placeholder="请输入供应商订单号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="paymentOrderNoNew" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <template slot="label"> <span style="color: red">新</span>支付单号 </template>
              <a-input v-model="formData.paymentOrderNoNew" placeholder="请输入支付单号" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="paymentTime" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <template slot="label"> <span style="color: red">新</span>付款时间 </template>
              <a-date-picker
                showTime
                valueFormat="YYYY-MM-DD HH:mm:ss"
                v-model="formData.paymentTime"
                style="width: 100%"
                placeholder="请选择付款时间"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item prop="paymentVoucherNew" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <template slot="label"> <span style="color: red">新</span>支付凭证 </template>
              <j-upload-oss v-model="formData.paymentVoucherNew" fileType="file" :number="1" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-spin>
    <template #footer>
      <a-button @click="clickCancel"> 取消 </a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit"> 提交 </a-button>
    </template>
    <!-- 产品选择弹窗 -->
    <product-check-modal
      v-if="showProductCheck"
      :defaultParam="{ deptCode: formData.costCenterId, supplyId }"
      :visible.sync="showProductCheck"
      :defaultData="formData.productDetailChangeList.filter((i) => !i.isOldProduct)"
      @submit="submitProductCheck"
    >
      <a-alert
        slot="hint"
        message="组合产品会按照组合比例拆分为子产品采购，列表仅显示产品对应的默认供应商"
        banner
        style="margin-bottom: 10px"
      />
    </product-check-modal>
  </j-modal>
</template>

<script>
import { formatAmount, parseNumber } from '@/utils/number'
import { getAction, postAction } from '@/api/manage'

import ProductCheckModal from '@/components/business/ProductCheckModal.vue'

export default {
  components: { ProductCheckModal },
  props: {
    // 要变更的采购单id，
    editId: {
      type: String,
      default: '',
    },
    // 是否显示弹框
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      modalVisible: this.visible,
      submitLoading: false,
      showProductCheck: false,
      formData: {
        productDetailChangeList: [],
      }, // 表单数据
      rules: {
        purchaser: [{ required: true, message: '请选择采购人!' }],
        costCenterId: [{ required: true, message: '请选择成本中心!' }],
        purchaseWay: [{ required: true, message: '请选择采购方式!' }],
        warehouse: [{ required: true, message: '请选择收货仓库!' }],
        transportWay: [{ required: true, message: '请选择运输方式!' }],
        settlementType: [{ required: true, message: '请选择结算类型!' }],
        settlementWay: [{ required: true, message: '请选择结算方式!' }],
        paymentWay: [{ required: true, message: '请选择支付方式!' }],
        shippingFeeOld: [{ required: true, message: '请输入运费!' }],
        shippingFeeNew: [{ required: true, message: '请输入新运费!' }],
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      url: {
        add: `/hzkj-purchase/purchase/change/order/add`,
        queryById: `/hzkj-purchase/purchase/order/info/detail`,
      },
      formColumns: [
        {
          title: '序号',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender(t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: 'SKU',
          width: 110,
          align: 'center',
          dataIndex: 'skuCode',
        },
        {
          title: '主图',
          width: 110,
          align: 'center',
          scopedSlots: { customRender: 'imgSlot' },
        },
        {
          title: '产品信息',
          width: 200,
          scopedSlots: { customRender: 'detailSlot' },
        },
        {
          title: '供应商',
          width: 300,
          scopedSlots: { customRender: 'supplierSlot' },
        },
        {
          title: '采购入库关系',
          width: 150,
          scopedSlots: { customRender: 'specSlot' },
        },
        {
          title: '原采购数量',
          width: 150,
          dataIndex: 'purchaseQuantityOld',
          customRender(t, record) {
            return record.isOldProduct ? record.purchaseQuantityOld : 0
          },
        },
        {
          title: '采购在途',
          width: 150,
          dataIndex: 'transitQuantity',
        },
        {
          slots: { title: 'purchaseQuantityNew' },
          width: 130,
          align: 'center',
          scopedSlots: { customRender: 'purchaseQuantityNewSlot' },
        },
        {
          title: '采购单价(元)',
          width: 120,
          align: 'center',
          dataIndex: 'unitPriceOld',
          customRender(t, record) {
            return record.isOldProduct ? record.unitPriceOld : '-'
          },
        },
        {
          title: '采购总价(元)',
          width: 120,
          align: 'center',
          customRender(t, record) {
            if (!record.isOldProduct) {
              return '-'
            }
            return formatAmount(record.unitPriceOld * record.purchaseQuantityOld, 3)
          },
        },
        {
          width: 120,
          align: 'center',
          slots: { title: 'unitPriceNew' },
          scopedSlots: { customRender: 'unitPriceNewSlot' },
        },
        {
          width: 120,
          align: 'center',
          slots: { title: 'totalPriceNew' },
          customRender(t, record) {
            return formatAmount(parseNumber(record.unitPriceNew) * parseNumber(record.purchaseQuantityNew), 3)
          },
        },
        {
          title: '操作',
          align: 'center',
          width: 70,
          scopedSlots: { customRender: 'action' },
        },
      ],
    }
  },
  computed: {
    supplyId() {
      if (!this.formData.productDetailChangeList.length) {
        return ''
      }
      return this.formData.productDetailChangeList[0].supplierId
    },
    totalAmountOld() {
      if (!this.formData.productDetailChangeList.length || !this.formData.shippingFeeOld) {
        return 0
      }
      // 小数计算js有误差，处理一下
      let total = this.formData.productDetailChangeList
        .filter((i) => i.isOldProduct)
        .reduce((total, next) => {
          return parseNumber(next.unitPriceOld) * parseNumber(next.purchaseQuantityOld) + total
        }, 0)
      return formatAmount(total + parseNumber(this.formData.shippingFeeOld), 3)
    },
    totalAmountNew() {
      if (!this.formData.productDetailChangeList.length || !this.formData.shippingFeeNew) {
        return 0
      }
      // 小数计算js有误差，处理一下
      let total = this.formData.productDetailChangeList.reduce((total, next) => {
        return parseNumber(next.unitPriceNew) * parseNumber(next.purchaseQuantityNew) + total
      }, 0)
      return formatAmount(total + parseNumber(this.formData.shippingFeeNew), 3)
    },
    purchaseTotalOld() {
      if (!this.formData.productDetailChangeList.length) {
        return 0
      }
      return this.formData.productDetailChangeList
        .filter((i) => i.isOldProduct)
        .reduce((total, next) => {
          return total + parseNumber(next.purchaseQuantityOld)
        }, 0)
    },
    purchaseTotalNew() {
      if (!this.formData.productDetailChangeList.length) {
        return 0
      }
      return this.formData.productDetailChangeList.reduce((total, next) => {
        return total + parseNumber(next.purchaseQuantityNew)
      }, 0)
    },
  },
  watch: {
    modalVisible(val) {
      this.$emit('update:visible', val)
    },
  },
  methods: {
    optionWarehouseDiy(result) {
      return result.map((item) => {
        return {
          ...item,
          value: item.id,
          text: `${item.name}[${item.code}]`,
        }
      })
    },
    //删除产品
    delProduct(index) {
      this.formData.productDetailChangeList.splice(index, 1)
    },
    async submitProductCheck(arr) {
      let endArr = [] // 最终需要保存的数据
      const joinDataFun = (i) => {
        // 新添加的单品
        let data = {
          pdArchiveId: i.id,
          category: i.category,
          categoryName: i.category_dictText,
          color: i.hzArchiveInfoOtherList[0].color,
          imgUrl: i.hzArchiveInfoImgsList.find((i2) => i2.izMaster == 1).url,
          heig: i.hzArchiveInfoOtherList[0].heig,
          len: i.hzArchiveInfoOtherList[0].len,
          widt: i.hzArchiveInfoOtherList[0].widt,
          gw: i.hzArchiveInfoOtherList[0].gw,
          singleSpec:
            i.hzArchiveInfoOtherList[0].len +
            '*' +
            i.hzArchiveInfoOtherList[0].widt +
            '*' +
            i.hzArchiveInfoOtherList[0].heig,
          nameCn: i.nameCn,
          nameEn: i.nameEn,
          purchaseQuantityNew: undefined,
          qualityType: i.hzArchiveInfoOtherList[0].qualityType,
          size: i.hzArchiveInfoOtherList[0].size,
          skuCode: i.skuCode,
          totalPrice: i.totalPrice,
          unitPriceNew: undefined,
          isOldProduct: false,
        }
        // 以下是供应商信息
        const defaultSupplier = (i.hzArchiveInfoSupplierList || []).find((i2) => i2.izDefault == 1)
        if (defaultSupplier) {
          if (this.formData.purchaseWay == '2' || defaultSupplier.type == 1) {
            // 当采购类型为其他时可以添加任意类型供应商，如果是16888采购，则只能添加16888供应商
            data = {
              ...data,
              supplierType: defaultSupplier.type,
              supplierName: defaultSupplier.name,
              url: defaultSupplier.url,
              attribute: defaultSupplier.type == 1 ? JSON.parse(defaultSupplier.attribute) : defaultSupplier.attribute,
              lowCount: defaultSupplier.lowCount,
              specsMy: defaultSupplier.specsMy,
              specsSup: defaultSupplier.specsSup,
              offerId: defaultSupplier.offerId,
              specId: defaultSupplier.specId,
              supplierId: defaultSupplier.supplierId,
              productSupperId: defaultSupplier.id,
            }
          }
        }
        endArr.push(data)
      }
      arr.forEach((item) => {
        if (!item.constituteStatus) {
          // 说明是之前已经添加的产品，数据已经处理完成，直接加入列表
          endArr.push(item)
        } else {
          if (item.constituteStatus == 2) {
            // 新添加的组合产品，组合产品自动拆分为添加组合产品下的所有单品
            item.hzArchiveInfoCproductAllInfoList.forEach((i2) => {
              joinDataFun(i2)
            })
          } else {
            joinDataFun(item)
          }
        }
      })
      // 先把不允许删除的产品数据保存起来
      let oldProductArr = this.formData.productDetailChangeList.filter((i) => i.isOldProduct)
      endArr = this.$Jlodash.uniqBy(endArr, 'skuCode') //组合产品的子产品和单品可能重复，需要去重
      endArr = endArr.filter((i) => !oldProductArr.some((i2) => i2.skuCode == i.skuCode)) // 如果新添加的数据有重复的，优先保存旧的数据
      this.formData.productDetailChangeList = [...oldProductArr, ...endArr] //组合产品的子产品和单品可能重复，需要去重
    },
    clickCancel() {
      this.$confirm({
        content: (h) => {
          return h(
            'div',
            {
              domProps: {
                innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">取消将不会保存当前单据的修改信息</div>你还要继续吗？</div>`,
              },
            },
            []
          )
        },
        onOk: () => {
          this.modalVisible = false
        },
      })
      return false
    },
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm({
            content: (h) => {
              return h(
                'div',
                {
                  domProps: {
                    innerHTML: `<div style="padding-left: 40px;"><div style="font-weight: bold;">提交确认</div><span style="color:red">原采购单将直接更新不可恢复</span>，你还要继续吗？</div>`,
                  },
                },
                []
              )
            },
            onOk: () => {
              const sendData = JSON.parse(JSON.stringify(this.formData))
              sendData.productDetailChangeList = sendData.productDetailChangeList.map((item) => {
                let end = {
                  ...item,
                  attribute: item.supplierType == 1 ? JSON.stringify(item.attribute) : item.attribute,
                  totalPriceNew: formatAmount(item.unitPriceNew * item.purchaseQuantityNew, 3),
                }
                if (item.isOldProduct) {
                  end.totalPriceOld = formatAmount(item.unitPriceOld * item.purchaseQuantityOld, 3)
                }
                return end
              })
              sendData.totalAmountOld = this.totalAmountOld
              sendData.totalAmountNew = this.totalAmountNew
              sendData.purchaseTotalOld = this.purchaseTotalOld
              sendData.purchaseTotalNew = this.purchaseTotalNew
              sendData.productAmountOld = formatAmount(this.totalAmountOld - this.formData.shippingFeeOld, 3)
              sendData.productAmountNew = formatAmount(this.totalAmountNew - this.formData.shippingFeeNew, 3)
              this.submitLoading = true
              postAction(this.url.add, sendData)
                .then((res) => {
                  if (res.success) {
                    this.$message.success('操作成功')
                    this.$emit('submit')
                    this.modalVisible = false
                  } else {
                    this.$message.error(res.message)
                  }
                })
                .finally(() => {
                  this.submitLoading = false
                })
            },
          })
        }
      })
    },
  },
  created() {
    // 有editId表示编辑账号
    if (this.editId) {
      // 编辑，需要回显
      this.submitLoading = true
      getAction(this.url.queryById, { id: this.editId }).then((res) => {
        if (res.success) {
          this.formData = {
            id: res.result.id,
            trackingNumberOld: res.result.trackingNumber,
            relateOrderNo: res.result.orderNo,
            purchaser: res.result.purchaser,
            costCenterId: res.result.costCenterId,
            purchaseWay: res.result.purchaseWay,
            warehouse: res.result.warehouse,
            transportWay: res.result.transportWay,
            expectArrivalTime: res.result.expectArrivalTime,
            warehouseRemark: res.result.warehouseRemark,
            remark: res.result.remark,
            changeCause: null,
            shippingFeeOld: res.result.totalShippingFee,
            shippingFeeNew: undefined,
            settlementType: res.result.settlementType,
            settlementWay: res.result.settlementWay,
            paymentWay: res.result.paymentWay,
            supplierOrderNoOld: res.result.supplierOrderNo,
            paymentOrderNoOld: res.result.paymentOrderNo,
            paymentTimeOld: res.result.paymentTime,
            paymentVoucherOld: res.result.paymentVoucher,
            supplierOrderNoNew: null,
            paymentOrderNoNew: null,
            paymentTime: null,
            paymentVoucherNew: undefined,
            productDetailChangeList: res.result.productDetailList.map((i) => ({
              ...i,
              attribute: i.supplierType == '1' ? JSON.parse(i.attribute) : i.attribute,
              purchaseQuantityOld: i.purchaseQuantity,
              purchaseQuantityNew: undefined,
              unitPriceOld: i.unitPrice,
              unitPriceNew: undefined,
              isOldProduct: true,
            })),
          }
          this.submitLoading = false
        } else {
          this.$message.warning(res.message)
        }
      })
    }
  },
}
</script>

<style lang="less" scoped>
.btn-box {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
.popover-preview-box {
  width: 300px;
  height: 300px;
  position: relative;
  background-color: #fafafa;
  img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
.img-box {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  display: inline-block;
  cursor: pointer;
  position: relative;
  background-color: #fafafa;
  img {
    width: 100%;
    height: 100%;
  }
}
.c-red {
  color: #ff4d4f;
}
.input-number-unit {
  display: inline-block;
  margin-left: -2px;
  width: 20%;
  color: rgba(0, 0, 0, 0.65);
  font-weight: 400;
  font-size: 14px;
  text-align: center;
  line-height: 30px;
  background-color: #fafafa;
  border: 1px solid #d9d9d9;
  border-radius: 0 4px 4px 0;
}

.pay-msg {
  font-weight: bold;
  font-size: 15px;
  padding: 5px 5px 15px;
}
.link-item {
  display: flex;
  .link {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }
}
.old-size {
  color: grey;
  text-decoration: line-through;
}
</style>
